/*
数据处理
 */

import featureAbility from '@ohos.ability.featureAbility';
import dataAbility from '@ohos.data.dataAbility';
import dataRdb from '@ohos.data.rdb';
import {Book} from '../model/bookModel';
import prompt from '@ohos.prompt';

const STORE_CONFIG_LIBRARY = {name : "library.db"}
const STORE_CONFIG_USER = { name: "user.db" }
const STORE_CONFIG_BOOK = { name: "book.db" }
//const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS book(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, introduction TEXT NOT NULL)'
let rdbStore_book: dataRdb.RdbStore = undefined
let rdbStore_library: dataRdb.RdbStore = undefined
let rdbStore_user: dataRdb.RdbStore = undefined
const TAG = '[DataManagementAbility].data'
/* Api测试
https://api.jike.xyz/situ/book/isbn/9787517097471?apikey=13173.30a420b0534ebad43ec1d24ba998a819.bcc3a14888c4568574c78165ac62d488
{"ret":0,
"msg":"请求成功",
"data":{
"id":9787517097471,
"name":"深入浅出OpenHarmony——架构、内核、驱动及应用开发全栈",
"subname":"",
"author":"李传钊",
"translator":null,
"publishing":"中国水利水电出版社",
"published":"2021",
"designed":"",
"code":"9787517097471",
"douban":35581417,
"doubanScore":0,
"numScore":1,
"brand":null,
"weight":null,
"size":null,
"pages":"304",
"photoUrl":"https://www.bookcovers.cn/index.php?client=szlib&isbn=9787517097471/cover",
"localPhotoUrl":"",
"price":"CNY88.00",
"froms":"douban_api2",
"num":0,
"createTime":"2022-07-28T13:55:58",
"uptime":"2022-07-28T13:55:58",
"authorIntro":"",
"description":"本书是由华为资深高级软件工程师、首位HarmonyOS&nbsp;HDE（Huawei Developer Expert）李传钊老师亲自编写的OpenHarmony操作系统技术图书。  本书从OpenHarmony操作系统的设计目标与设计思路开始，由表及里、深入浅出地讲解了OpenHarmony操作系统的架构、内核、驱动及应用开发基础与实战的全栈技术内容。在实战部分，从开发环境的安装配置开始，分别讲解了南向开发、北向开发的基本过程及实战案例。本书的英文版已在翻译之中，华为已将其作为面向全球推荐的OpenHarmony操作系统的官方技术教程之一。  本书可作为OpenHarmony操作系统开发人员、技术爱好者的自学或参考资料，也可作为高校相关专业的教材。",
"reviews":null,
"tags":null}
}
*/

/**
 * table管理器
 * tableManager
 */
namespace tableManager{
    //user.db
    export const table_name_admin = 'admin';
    export const table_name_admin_todo = 'adminTodo';
    export const table_name_reader = 'reader';
    //book.db
    export const table_name_book = 'book';
    //library.db
    export const table_name_library_root = 'Level1_root';
    export const table_name_library_book = 'Level4_book';
    /*
    书籍位置信息库
    - 层1：数据库根节点：{institutionName,tableName}//32个字符以内
    - 层2：具体场馆：{libraryName,tableName}
    - 层3：书架及分区：{bookshelfBlockId,position,note,tableName}
    - 层4：书籍：{bookID,inBookshelfBlock,positionRank}
     */
    /**
     * 生成表名字符串
     * @param level:number in [1,2,3,4]
     * @param tableName
     */
    export function libraryRdb_generateTableName(level:number,tableName:string){
        var table_level :string = 'Level';
        return table_level + level + tableName;
    };
    /**
     * 生成创建表的SQL语句
     * @param level in [1,2,3,4]//书籍位置信息库,
     * @param level in [10]//书籍信息库,
     * @param level in [11,12,13]//用户信息库,11:admin,12:reader,13:todoItem
     * @param tableName 完整tableName
     */
    export function generateSql(level:number,tableName:string){
        if([1,2,3,4,10,11,12,13].includes(level)){
            let columns :string = '';
            switch(level){
                case 1:{
                    //层1：数据库根节点：{institutionName,tableName}
                    columns = 'institutionName TINYTEXT NOT NULL,tableName TINYTEXT NOT NULL';
                    break;
                }
                case 2:{
                    //层2：具体场馆：{libraryName,tableName}
                    columns = 'libraryName TINYTEXT NOT NULL,tableName TINYTEXT NOT NULL';
                    break;
                }
                case 3:{
                    //层3：书架及分区：{bookshelfBlockId,position,note,tableName,usedSpace}
                    columns = 'bookshelfBlockId TINYTEXT NOT NULL,position TINYTEXT NOT NULL,note TEXT NOT NULL,tableName TINYTEXT NOT NULL,usedSpace TINYTEXT NOT NULL';
                    break;
                }
                case 4:{
                    //层4：书籍：{bookId,bookSortId,inBookshelfBlock,positionRank,status}
                    columns = 'bookId TEXT NOT NULL,bookSortId TEXT NOT NULL,inBookshelfBlock TEXT,positionRank TEXT,status TEXT';
                    break;
                }
                case 10:{
                    //书籍：{sortId,name,subname,isbn,author,translator,publishing,published,pages,photoUrl,localPhotoUrl,authorInfo,description,content}
                    columns = 'sortId TINYTEXT,name TEXT,subname TEXT,isbn TINYTEXT NOT NULL,' +
                    'author TINYTEXT,translator TINYTEXT,publishing TINYTEXT,published TINYTEXT,pages INT,' +
                    'photoUrl TEXT,localPhotoUrl TEXT,authorInfo TEXT,description TEXT,content TEXT';
                    break;
                }
                case 11:{
                    //管理员：{id:string,permission:number,name:string,password:string,token:string}
                    columns = 'id TINYTEXT NOT NULL,permission INT NOT NULL,name TINYTEXT,password TINYTEXT NOT NULL,token TINYTEXT NOT NULL';
                    break;
                }
                case 12:{
                    //读者：{id:string,permission:number,name:string,password:string,token:string,lend:json},lend:{id:xxxx,backTime:xxxx}
                    columns = 'id TINYTEXT NOT NULL,permission INT NOT NULL,name TINYTEXT,password TINYTEXT NOT NULL,token TINYTEXT NOT NULL,lend TEXT NOT NULL';
                    break;
                }
                case 13:{
                    //待办事项：{todoType,todoId,todoText}
                    columns = 'todoType TINYTEXT NOT NULL,todoId TINYTEXT NOT NULL,todoText TEXT NOT NULL';
                    break;
                }
            }
            return `CREATE TABLE IF NOT EXISTS ${tableName}(${columns});`;
        }
        else{
            console.error('generateSql error: level:'+level);
            return null;
        }
    };
    /**
     * book.db初始化
     * @param rdb
     */
    export function bookRdbInit(rdb:dataRdb.RdbStore){
        rdb.executeSql(tableManager.generateSql(10,tableManager.table_name_book),null,
            (err)=>{
                console.info("bookRdbInit executeSql: "+tableManager.generateSql(10,tableManager.table_name_book));
                if(err){
                    console.info("bookRdbInit executeSql failed, err: " + err);
                    return;
                }
                console.info("bookRdbInit executeSql success");
            }
        );
    }
    /**
     * library.db初始化
     * @param rdb
     */
    export function libraryRdbInit(rdb:dataRdb.RdbStore){
        rdb.executeSql(tableManager.generateSql(1,tableManager.table_name_library_root),null,
            (err)=>{
                console.info("libraryRdbInit executeSql1: "+tableManager.generateSql(1,tableManager.table_name_library_root))
                if(err){
                    console.info("libraryRdbInit executeSql1 failed, err: " + err);
                    return;
                }
                console.info("libraryRdbInit executeSql1 success");
            }
        );
        rdb.executeSql(tableManager.generateSql(2,tableManager.libraryRdb_generateTableName(2,'wut')),null,
            (err)=>{
                console.info("libraryRdbInit executeSql2: "+tableManager.generateSql(2,tableManager.libraryRdb_generateTableName(2,'wut')));
                if(err){
                    console.info("libraryRdbInit executeSql2 failed, err: " + err);
                    return;
                }
                console.info("libraryRdbInit executeSql2 success");
            }
        );
        rdb.executeSql(tableManager.generateSql(3,tableManager.libraryRdb_generateTableName(3,'nanhu')),null,
            (err)=>{
                console.info("libraryRdbInit executeSql3: "+tableManager.generateSql(3,tableManager.libraryRdb_generateTableName(3,'nanhu')));
                if(err){
                    console.info("libraryRdbInit executeSql3 failed, err: " + err);
                    return;
                }
                console.info("libraryRdbInit executeSql3 success");
            }
        );
        rdb.executeSql(tableManager.generateSql(3,tableManager.libraryRdb_generateTableName(3,'dongyuan')),null,
            (err)=>{
                console.info("libraryRdbInit executeSql3: "+tableManager.generateSql(3,tableManager.libraryRdb_generateTableName(3,'dongyuan')));
                if(err){
                    console.info("libraryRdbInit executeSql3 failed, err: " + err);
                    return;
                }
                console.info("libraryRdbInit executeSql3 success");
            }
        );
        rdb.executeSql(tableManager.generateSql(3,tableManager.libraryRdb_generateTableName(3,'xiyuan')),null,
            (err)=>{
                console.info("libraryRdbInit executeSql3: "+tableManager.generateSql(3,tableManager.libraryRdb_generateTableName(3,'xiyuan')));
                if(err){
                    console.info("libraryRdbInit executeSql3 failed, err: " + err);
                    return;
                }
                console.info("libraryRdbInit executeSql3 success");
            }
        );
        rdb.executeSql(tableManager.generateSql(4,tableManager.table_name_library_book),null,
            (err)=>{
                console.info("libraryRdbInit executeSql4: "+tableManager.generateSql(4,tableManager.table_name_library_book));
                if(err){
                    console.info("libraryRdbInit executeSql4 failed, err: " + err);
                    return;
                }
                console.info("libraryRdbInit executeSql4 success");
            }
        );
    }
    /**
     * user.db初始化
     * @param rdb
     */
    export function userRdbInit(rdb:dataRdb.RdbStore){
        rdb.executeSql(tableManager.generateSql(11,tableManager.table_name_admin),null,
            (err)=>{
                console.info("userRdbInit executeSql1: "+tableManager.generateSql(11,tableManager.table_name_admin))
                if(err){
                    console.info("userRdbInit executeSql1 failed, err: " + err);
                    return;
                }
                console.info("userRdbInit executeSql1 success");
            }
        );
        rdb.executeSql(tableManager.generateSql(12,tableManager.table_name_reader),null,
            (err)=>{
                console.info("userRdbInit executeSql2: "+tableManager.generateSql(12,tableManager.table_name_reader))
                if(err){
                    console.info("userRdbInit executeSql2 failed, err: " + err);
                    return;
                }
                console.info("userRdbInit executeSql2 success");
            }
        );
        rdb.executeSql(tableManager.generateSql(13,tableManager.table_name_admin_todo),null,
            (err)=>{
                console.info("userRdbInit executeSql3: "+tableManager.generateSql(13,tableManager.table_name_admin_todo))
                if(err){
                    console.info("userRdbInit executeSql3 failed, err: " + err);
                    return;
                }
                console.info("userRdbInit executeSql3 success");
            }
        );
    }
}

function analyzeUri(uri:string):string[]{
    /*
    uri结构
    scheme：协议方案名，固定为“dataability”，代表Data Ability所使用的协议类型
    authority：设备ID。如果为跨设备场景，则为目标设备的ID；如果为本地设备场景，则不需要填写
    path：资源的路径信息，代表特定资源的位置信息
    query：查询参数
    fragment：可以用于指示要访问的子资源
    注:scheme与后面部分用"://"分隔,其后参数之间用"/"分隔
    eg:"dataability:///com.lx_wut.libraryManageSystem.DataManagementAbility//user.admin"
    eg:"dataability:///com.lx_wut.libraryManageSystem.DataManagementAbility/tableName/library.4"
     */
    var [query,fragment] = uri.substring(68).split('/');
    return [query,fragment];
}

export default {
    onInitialized(abilityInfo) {
        console.info(`${TAG} DataAbility onInitialized`)
        console.info(`${TAG} create table begin`)
        let context = featureAbility.getContext();
        console.info(`${TAG} getContext : ${JSON.stringify(context)}`);
        //连接book.db
        dataRdb.getRdbStore(context, STORE_CONFIG_BOOK, 1, (err, rdb) => {
            if (err) {
                console.info(`${TAG} create table_book err = ${JSON.stringify(err)}`);
                return;
            }
            console.info(`${TAG} create table_book done`)
            tableManager.bookRdbInit(rdb);
            rdbStore_book = rdb;
            prompt.showToast({
                message:"连接book.db成功",
            })
            console.info(`${TAG} create table_book successfully`)
        })
        //连接library.db
        dataRdb.getRdbStore(context, STORE_CONFIG_LIBRARY, 1, (err, rdb) => {
            if (err) {
                console.info(`${TAG} create table_library err = ${JSON.stringify(err)}`);
                return;
            }
            console.info(`${TAG} create table_library done`)
            tableManager.libraryRdbInit(rdb);
            rdbStore_library = rdb;
            prompt.showToast({
                message:"连接library.db成功",
            })
            console.info(`${TAG} create table_library successfully`)
        })
        //连接user.db
        dataRdb.getRdbStore(context, STORE_CONFIG_USER, 1, (err, rdb) => {
            if (err) {
                console.info(`${TAG} create table_user err = ${JSON.stringify(err)}`);
                return;
            }
            console.info(`${TAG} create table_user done`)
            tableManager.userRdbInit(rdb);
            rdbStore_user = rdb;
            prompt.showToast({
                message:"连接user.db成功",
            })
            console.info(`${TAG} create table_user successfully`)
            //默认管理员账号初始化
//            let predicates = new dataRdb.RdbPredicates("admin");
//            predicates.equalTo('id','0000000000000');
//            rdbStore_user.query(predicates,['id'],(err,resultSet)=>{
//                if (err.code) {
//                    console.info("onInitialized Query failed, err: " + JSON.stringify(err))
//                    return;
//                }
//                if(resultSet.rowCount){
//                    console.info("onInitialized Query successful,the admin existed");
//                    prompt.showToast({
//                        message:"数据库初始化成功",
//                    })
//                }
//                else{
//                    console.info("onInitialized Query successful,the admin not existed");
//                    rdbStore_user.insert('admin',{id:"0000000000000",permission:2,name:"admin",password:"admin",token:"1234567890"},
//                        (err,ret)=>{
//                            if (err.code) {
//                                console.info("onInitialized Insert failed, err: " + JSON.stringify(err))
//                                return;
//                            }
//                            prompt.showToast({
//                                message:"数据库初始化成功",
//                            })
//                            console.info("onInitialized Insert admin done: " + ret);
//                        })
//                }
//            })
        })
    },

    insert(uri, valueBucket, callback,) {
        var [query,fragment] = analyzeUri(uri);
        console.info(TAG + ' insert start' + uri);
        console.info(TAG + ' query:' + query + ' fragment:' + fragment);
        switch(fragment){
            case 'user.admin':{
                rdbStore_user.insert(tableManager.table_name_admin, valueBucket, callback);
                break;
            }
            case 'user.adminTodo':{
                rdbStore_user.insert(tableManager.table_name_admin_todo, valueBucket, callback);
                break;
            }
            case 'user.reader':{
                rdbStore_user.insert(tableManager.table_name_reader, valueBucket, callback);
                break;
            }
            case 'book':{
                rdbStore_book.insert(tableManager.table_name_book, valueBucket, callback);
                break;
            }
            case 'library.1':{
                rdbStore_library.insert(tableManager.table_name_library_root, valueBucket, callback);
                break;
            }
            case 'library.2':{
                rdbStore_library.insert(query, valueBucket, callback);
                break;
            }
            case 'library.3':{
                rdbStore_library.insert(query, valueBucket, callback);
                break;
            }
            case 'library.4':{
                rdbStore_library.insert(tableManager.table_name_library_book, valueBucket, callback);
                break;
            }
        }
    },

/*    batchInsert(uri, valueBuckets, callback) {
//        console.info(TAG + ' batch insert start')
//        var [query,fragment] = analyzeUri(uri);
//        let rdbStore : dataRdb.RdbStore;
//        switch(fragment){
//            case 'user':{
//                rdbStore = rdbStore_user;
//                break;
//            }
//            case 'book':{
//                rdbStore = rdbStore_book;
//                break;
//            }
//            case 'library':{
//                rdbStore = rdbStore_library;
//                break;
//            }
//        }
//        for (let i = 0;i < valueBuckets.length; i++) {
//            console.info(TAG + ' batch insert i=' + i)
//            if (i < valueBuckets.length - 1) {
//                rdbStore.insert(TABLE_NAME, valueBuckets[i], (err: any, num: number) => {
//                    console.info(TAG + ' batch insert ret=' + num)
//                })
//            } else {
//                rdbStore.insert(TABLE_NAME, valueBuckets[i], callback)
//            }
//        }
//    },
*/

    query(uri, columns, predicates, callback) {
        console.info(TAG + ' query start' + uri);
        var [query,fragment] = analyzeUri(uri);
        console.info(TAG + ' query:' + query + ' fragment:' + fragment);
        switch(fragment){
            case 'user.admin':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_admin, predicates)
                rdbStore_user.query(rdbPredicates, columns, callback)
                break;
            }
            case 'user.adminTodo':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_admin_todo, predicates)
                rdbStore_user.query(rdbPredicates, columns, callback)
                break;
            }
            case 'user.reader':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_reader, predicates)
                rdbStore_user.query(rdbPredicates, columns, callback)
                break;
            }
            case 'book':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_book, predicates)
                rdbStore_book.query(rdbPredicates, columns, callback)
                break;
            }
            case 'library.1':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_library_root, predicates)
                rdbStore_library.query(rdbPredicates, columns, callback)
                break;
            }
            case 'library.2':{
                let rdbPredicates = dataAbility.createRdbPredicates(query, predicates)
                rdbStore_library.query(rdbPredicates, columns, callback)
                break;
            }
            case 'library.3':{
                let rdbPredicates = dataAbility.createRdbPredicates(query, predicates)
                rdbStore_library.query(rdbPredicates, columns, callback)
                break;
            }
            case 'library.4':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_library_book, predicates)
                rdbStore_library.query(rdbPredicates, columns, callback)
                break;
            }
        }
    },
    update(uri, valueBucket, predicates, callback) {
        console.info(TAG + ' update start' + uri);
        var [query,fragment] = analyzeUri(uri);
        console.info(TAG + ' query:' + query + ' fragment:' + fragment);
        let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_library_root, predicates)
        rdbStore_library.update(valueBucket, rdbPredicates, callback)
        switch(fragment){
            case 'user.admin':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_admin, predicates)
                rdbStore_user.update(valueBucket, rdbPredicates, callback)
                break;
            }
            case 'user.adminTodo':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_admin_todo, predicates)
                rdbStore_user.update(valueBucket, rdbPredicates, callback)
                break;
            }
            case 'user.reader':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_reader, predicates)
                rdbStore_user.update(valueBucket, rdbPredicates, callback)
                break;
            }
            case 'book':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_book, predicates)
                rdbStore_book.update(valueBucket, rdbPredicates, callback)
                break;
            }
            case 'library.1':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_library_root, predicates)
                rdbStore_library.update(valueBucket, rdbPredicates, callback)
                break;
            }
            case 'library.2':{
                let rdbPredicates = dataAbility.createRdbPredicates(query, predicates)
                rdbStore_library.update(valueBucket, rdbPredicates, callback)
                break;
            }
            case 'library.3':{
                let rdbPredicates = dataAbility.createRdbPredicates(query, predicates)
                rdbStore_library.update(valueBucket, rdbPredicates, callback)
                break;
            }
            case 'library.4':{
                let rdbPredicates = dataAbility.createRdbPredicates(tableManager.table_name_library_book, predicates)
                rdbStore_library.update(valueBucket, rdbPredicates, callback)
                break;
            }
        }
    },
    delete(uri, predicates, callback) {
        console.info(TAG + ' delete start' + uri)
        var [query,fragment] = analyzeUri(uri);
        console.info(TAG + ' query:' + query + ' fragment:' + fragment);
        let rdbStore : dataRdb.RdbStore;
        let tableName : string;
        switch(fragment){
            case 'user.admin':{
                tableName = tableManager.table_name_admin;
                rdbStore = rdbStore_user;
                break;
            }
            case 'user.adminTodo':{
                tableName = tableManager.table_name_admin_todo;
                rdbStore = rdbStore_user;
                break;
            }
            case 'user.reader':{
                tableName = tableManager.table_name_reader;
                rdbStore = rdbStore_user;
                break;
            }
            case 'book':{
                tableName = tableManager.table_name_book;
                rdbStore = rdbStore_book;
                break;
            }
            case 'library.1':{
                tableName = tableManager.table_name_library_root;
                rdbStore = rdbStore_library;
                break;
            }
            case 'library.2':{
                tableName = query;
                rdbStore = rdbStore_library;
                break;
            }
            case 'library.3':{
                tableName = query;
                rdbStore = rdbStore_library;
                break;
            }
            case 'library.4':{
                tableName = tableManager.table_name_library_book;
                rdbStore = rdbStore_library;
                break;
            }
        }
        let rdbPredicates = dataAbility.createRdbPredicates(tableName, predicates)
        rdbStore.delete(rdbPredicates, callback);
    }
};